from functools import wraps
from flask import request, g

from libs.error_code import Forbidden


def validation(validate_name=None):
    def wrapper(func):
        @wraps(func)
        def _(*args, **kwargs):
            method_vname = validate_name.split(':')
            if len(method_vname) > 1:
                method = [method_vname[0]]
                vname = method_vname[1]
            else:
                method = ['GET', 'POST', 'DELETE', "PUT"]
                vname = method_vname[0]
            if request.method in method and g.current_user.role != 'ssa1':
                user = g.current_user
                own_power = user.own_power

                if vname not in own_power:
                    return Forbidden()
            return func(*args, **kwargs)

        return _

    return wrapper


def check_header(product):
    def wrapper(func):
        @wraps(func)
        def _(*args, **kwargs):
            headers = request.headers
            header_product = headers.get('product')
            if header_product not in product:
                return Forbidden()
            return func(*args, **kwargs)

        return _

    return wrapper
